﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Diagnostics;

using Qplus.Infrastructure;
using Qplus.beans;
using Qplus.enums;
using Qplus.protocol;
using System.Runtime.CompilerServices;
using System.Threading;

namespace Qplus.UI
{
    public class LoginHelper : IPacketListener
    {
        String version = "1000";
        static LoginHelper instance;
        public delegate void StateChanged(LoginHelper sender, UIEvent args);
        public event StateChanged onStateChanged;
        public event EventHandler<UIEvent> loginevent;
        public event EventHandler<UIEvent> enterRoomEvent;
        public event EventHandler<UIEvent> receiveRoomMsgEvent;

        public static LoginHelper Instance { get { if (null == instance)instance = new LoginHelper(); return instance; } }
        public LoginHelper()
        {
            loginevent += new EventHandler<UIEvent>(LoginHelper_loginevent);
            enterRoomEvent += new EventHandler<UIEvent>(LoginHelper_chatroomevent);
            receiveRoomMsgEvent += new EventHandler<UIEvent>(LoginHelper_receiveMsgEvent);
            //onStateChanged = new StateChanged(LoginHelper_loginevent);
        }

        void LoginHelper_receiveMsgEvent(object sender, UIEvent e)
        {
            //throw new NotImplementedException();
        }

        void LoginHelper_chatroomevent(object sender, UIEvent e)
        {
            //throw new NotImplementedException();
        }

        void LoginHelper_loginevent(object sender, UIEvent e)
        {
            //throw new NotImplementedException();
            int i=0;
            ++i;
        }

        public void onLoginVerify(int result, string ip, int port,
            byte[] key, long userID, String upurl)
        {
            QUser user = QplusT.getInstance().getUser();
            switch (result)
            {
                case 0:
                    if (user != null)
                    {
                        user.key = key;
                        //user.setKey(key);
                        user.getInfo().setUserID(userID);
                        user.url = upurl;
                        user.userID = userID;
                    }
                    QplusT.getInstance().loginUserServer(ip, port, version, "", key, userID);
                    Debug.WriteLine("验证成功");
                    break;
                case 1:
                    QplusT.changeLoginState(user, false, false);
                    //			if(user != null){
                    //				user.setKey(null);
                    //				user.setUserID(-1);
                    //				user.notifyObservers();
                    //			}
                    ConnectionManager.getInstance().closeConnection();
                    Debug.WriteLine("", "验证失败");
                    break;

                default:
                    break;
            }
        }

        public void onLogout(int result)
        {
            ConnectionManager.getInstance().closeConnection();
            QUser user = QplusT.getInstance().getUser();
            QplusT.changeLoginState(user, false, false);
            //KeepAlive.stopKeepAlive();
        }


        public void onLoginUserServer(int result, long appID, E_USER_LEVEL level)
        {
            QUser user = QplusT.getInstance().getUser();
            switch (result)
            {
                case 0:
                    user.appID = appID;
                    user.getInfo().setUserLevel(level);
                    //user.getInfo().notifyObservers();
                    QplusT.changeLoginState(user, false, true);
                    Debug.WriteLine("登陆成功");
                    user.setForceLogout(false);
                    processLoginUserServer();
                    //QplusT.Instance.startKeepAlive();
                    break;
                case 1:
                    QplusT.changeLoginState(user, false, false);

                    Debug.WriteLine("登录失败");
                    break;

                default:
                    break;
            }
        }


	    public virtual void packetEvent(PacketEvent Pevent)
        {
#if ff
            #region LTW
            InPacket packet = Pevent.myPacket;
            if (packet == null)
            {
                return;
            }
            else
            {
                int id = packet.getMsgID();
                MMessageID MID = (MMessageID)packet.getMsgID();
                switch ((MMessageID)packet.getMsgID())
                {
#region LOG 3000
                    case MMessageID.L2C_RESP_LOGIN:
                        {
                            L2C_RESP_LOGIN p = (L2C_RESP_LOGIN)packet;
                            int result = p.getResult();
                            string ip = p.getIP();
                            int port = p.getPort();
                            byte[] key = p.getKey();
                            long userid = p.getUserID();
                            string url = p.getUpgradeURL();
                            onLoginVerify(result,ip,port,key,userid,url);
                            break;
                        }
                    case MMessageID.U2C_RESP_LOGIN:
                        {
                            U2C_RESP_LOGIN p = (U2C_RESP_LOGIN)packet;
                            int result = p.getResult();
                            long appid = p.getAppID();
                            int l = p.getUserLevel();
                            E_USER_LEVEL level = (E_USER_LEVEL)l;
                            onLoginUserServer(result, appid, level);
                            break;
                        }
                    case MMessageID.U2C_RESP_LOGOUT:
                        {
                            U2C_RESP_LOGOUT p = (U2C_RESP_LOGOUT)packet;
                            onLogout(p.getResult());
                            break;
                        }
#endregion
#region SYS MSG 3100
                    case MMessageID.U2C_NOTIFY_SYSTEM_MSG:
                    case MMessageID.U2C_SYN_FORCE_LOGOUT:
                    case MMessageID.C2U_REQ_SHORT_MSG:
                    case MMessageID.U2C_RESP_SHORT_MSG:
                    case MMessageID.U2C_NOTIFY_SHORT_MSG:
                        break;
#endregion
#region CUSTOM SERVICE 3200
                    case MMessageID.C2U_REQ_CUSTOMER_SERVICE:
                    case MMessageID.U2C_RESP_CUSTOMER_SERVICE:
                    case MMessageID.C2U_REQ_SESSION_BEGIN:
                    case MMessageID.U2C_RESP_SESSION_BEGIN:
                    case MMessageID.U2C_NOTIFY_SESSION_BEGIN:
                    case MMessageID.C2U_REQ_SESSION_END:
                    case MMessageID.U2C_RESP_SESSION_END:
                    case MMessageID.U2C_NOTIFY_SESSION_END:
                    case MMessageID.C2U_REQ_CHAT_SENDMSG: 
                    case MMessageID.U2C_RESP_CHAT_SENDMSG:
                    case MMessageID.U2C_NOTIFY_CHAT_RECVMSG:
                    case MMessageID.C2U_REQ_CHAT_VOICEBEGIN:
                    case MMessageID.U2C_RESP_CHAT_VOICEBEGIN:
                    case MMessageID.U2C_NOTIFY_CHAT_VOICEBEGIN:
                    case MMessageID.C2U_REQ_CHAT_VOICEDATA:
                    case MMessageID.U2C_NOTIFY_CHAT_VOICEDATA:
                    case MMessageID.C2U_REQ_CHAT_VOICEEND:
                    case MMessageID.U2C_RESP_CHAT_VOICEEND:
                    case MMessageID.U2C_NOTIFY_CHAT_VOICEEND:
                        break;
#endregion
#region ROOM
                    case MMessageID.U2C_RESP_ROOM_PEOPLE_COUNT:
                    case MMessageID.U2C_RESP_ENTER_ROOM:
                        {
                            U2C_RESP_ENTER_ROOM p = ((U2C_RESP_ENTER_ROOM)packet);
                            Debug.WriteLine(p.getMsgID().ToString());

                            processEnterRoomMsg();
                            break;
                        }
                    case MMessageID.U2C_RESP_LEAVE_ROOM:
                    case MMessageID.U2C_RESP_ROOM_SENDMSG:
                        {
                            //do something
                            break;
                        }
                    case MMessageID.U2C_NOTIFY_ROOM_RECVTMSG:
                        {
                            processReceiveRoomMsg(packet.getData());
                            break;
                        }
#endregion
                    default:
                        break;
                }
            }
            #endregion
#endif
// LJY
            Debug.WriteLine("PacketEvent: thread id = " + System.Threading.Thread.CurrentThread.ManagedThreadId);
            InPacket packet = Pevent.myPacket;
		    if(packet == null){
			    return;
            }
		    //验证
		    else if(packet is L2C_RESP_LOGIN){
			    L2C_RESP_LOGIN p = ((L2C_RESP_LOGIN) packet);
			    onLoginVerify(p.getResult(), p.getIP(),
						    p.getPort(), p.getKey(), p.getUserID(),
						    p.getUpgradeURL());
		    }
		    //登陆用户服务器
		    else if(packet is U2C_RESP_LOGIN){
			    U2C_RESP_LOGIN p = ((U2C_RESP_LOGIN) packet);
			    E_USER_LEVEL level = 0;
			    int l = p.getUserLevel();
			    if (l == (int)E_USER_LEVEL.EUL_GENERAL) {
				    level = E_USER_LEVEL.EUL_GENERAL;
			    } else if (l == (int)E_USER_LEVEL.EUL_SENIOR) {
				    level = E_USER_LEVEL.EUL_SENIOR;
			    } else if (l == (int)E_USER_LEVEL.EUL_CS) {
				    level = E_USER_LEVEL.EUL_CS;
			    }
			    onLoginUserServer(p.getResult(), p.getAppID(),
						    level);
		    }
		    //退出登录
		    else if(packet is U2C_RESP_LOGOUT){
			    U2C_RESP_LOGOUT p = ((U2C_RESP_LOGOUT) packet);
			    onLogout(p.getResult());
            }
                //聊天室
            else if (packet is U2C_RESP_ENTER_ROOM)
            {
                U2C_RESP_ENTER_ROOM p = ((U2C_RESP_ENTER_ROOM)packet);
                Debug.WriteLine(p.getMsgID().ToString());
                Room.CurrentRoomInstance.RoomID = p.getRoomID();
                processEnterRoomMsg();
            }
            else if (packet is U2C_RESP_LEAVE_ROOM)
            {

            }
            else if (packet is U2C_RESP_ROOM_SENDMSG)
            {
                //seccess or fail 
            }
            else if (packet is U2C_NOTIFY_ROOM_RECVTMSG)
            {
                processReceiveRoomMsg(packet.getData());
            }
            //单聊
            else if (packet is U2C_NOTIFY_CHAT_RECVMSG)
            {

            }
        }

        private void processLoginUserServer()
        {
            //if(null!=onStateChanged)
            //    onStateChanged(this, new UIEvent("ProcessIncomingMessage"));
            if (null != loginevent)
                loginevent(this, new UIEvent());
        }

        private void processEnterRoomMsg()
        {
            if(null!=enterRoomEvent)
            enterRoomEvent(this, new UIEvent());
        }

        private void processReceiveRoomMsg(byte[] msg)
        {
            if (null != receiveRoomMsgEvent)
                receiveRoomMsgEvent(this, new UIEvent(msg));
        }
    }
}
